<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Model\Admin\Category;

class CategoryController extends CommonController
{
		// get.admin/category
    public function index(){
    	$categorys = (new Category)->tree();
    	return view('admin.category.index')->with('data', $categorys);
    }

    // 更新排序
    public function changeOrder(){
    	$input = Input::all();
    	$cate = Category::find($input['cate_id']);
    	$cate->cate_order = $input['cate_order'];
    	$result = $cate->update();
    	if($result){
    		$data = [
    			'status' => '1',
    			'msg'  => '排序更新成功',
    		];
    	} else {
    		 $data = [
    		 	'status' => '0',
    		 	'msg' => '排序更新失败',
    		 ];
    	}
    	return $data;
    }

    // get.admin/category/create 分类添加界面显示
    public function create(){
    	$data = Category::where('cate_pid',0)->get();
    	return view('admin.category.add',compact('data'));
    }

    // post.admin/category 分类添加数据存储
    public function store(){
    	$input = Input::except('_token');
        $rules = [
    		'cate_name'  => 'required',

    	];
    	$messages = [
    		'cate_name.required'  => '分类名称必须填写！'
    	];
    	// validator 验证
    	$validator = Validator::make($input,$rules,$messages);
    	if($validator->passes()){
    		$result = Category::create($input); // 需要定义 $fillable / $guarded
	    	if($result){
	    		return redirect('admin/category');
	    	}else{
	    		return back()->with('errors','unknown error');
	    	}
    	}else{
    		return back()->withErrors($validator);
    	}   	
    }

    // admin/category/{category}/edit  编辑页面的显示
    public function edit($cate_id){
    	$cate = Category::find($cate_id);
    	$data = Category::where('cate_pid',0)->get();
    	return view('admin.category.edit',compact('cate','data'));
    } 

    // put admin/category/{category}  分类的数据修改
    public function update($cate_id){
    	$input = Input::except('_token','_method');
    	$result = Category::where('cate_id',$cate_id)->update($input);
    	if($result !== false){
    		return redirect('admin/category')->with('success','修改成功！');
    	}else{
    		return back()->with('errors','修改失败！');
    	}
    }

    // delete.admin/category/{category}
    public function destroy($cate_id){
    	$result = Category::where('cate_id',$cate_id)->delete();
    	if($result){
    		$data = [
    			'status'  =>   '1',
    			'msg'     =>   '分类删除成功',
    		];
    	}else{
    		$data = [
    			'status'  =>   '0',
    			'msg'     =>   '分类删除失败',
    		];
    	}
    	return $data;
    }

    // get admin/category/{category}
    public function show(){

    }
}

